<template>
  <view class="login-form">
    <view class="login-title">欢迎登录</view>
    <uni-forms style="margin-top: 100px" :modelValue="loginForm" :rules="rules" validate-trigger="bind">
      <uni-forms-item name="userName">
        <uni-easyinput type="text" v-model="loginForm.userName" prefix-icon="person" focus placeholder="用户名" />
      </uni-forms-item>
      <uni-forms-item name="password">
        <uni-easyinput type="password" v-model="loginForm.password" prefix-icon="locked" placeholder="密码" />
      </uni-forms-item>
    </uni-forms>
    <button class="form-button" @click="submit" type="primary">立即登录</button>
    <button class="form-button" @click="jumpToRegister()" type="info">没有账号？立即注册</button>
  </view>
</template>

<script lang="ts">
import { loginApi } from '../../api/login'

export default {
  data() {
    return {
      loginForm: {
        terminal: 1, // APP终端
        userName: '',
        password: ''
      },
      rules: {
        userName: {
          rules: [
            {
              required: true,
              errorMessage: '请输入用户名'
            }
          ]
        },
        password: {
          rules: [
            {
              required: true,
              errorMessage: '请输入密码'
            }
          ]
        }
      }
    }
  },
  methods: {
    submit() {
      loginApi.login(this.loginForm).then((data) => {
        console.log(data)
        console.log('登录成功,自动跳转到聊天页面...')
        uni.setStorageSync('loginInfo', data)
        // 调用App.vue的初始化方法
        getApp().init()
        // 跳转到聊天页面
        uni.switchTab({ url: '/pages/homepage/index' })
      })
    },
    jumpToRegister() {
      uni.navigateTo({ url: '/pages/register/index' })
    }
  },

  onLoad() {
    this.loginForm.userName = uni.getStorageSync('userName')
    this.loginForm.password = uni.getStorageSync('password')
    const loginInfo = uni.getStorageSync('loginInfo')
    if (loginInfo) {
      // 跳转到聊天页面
      uni.switchTab({ url: '/pages/homepage/index' })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-form {
  margin: 50rpx;

  .login-title {
    margin-top: 100rpx;
    margin-bottom: 100rpx;
    color: royalblue;
    text-align: center;
    font-size: 60rpx;
    font-weight: 600;
  }

  .form-button {
    margin-top: 20rpx;
    margin-bottom: 20rpx;
  }
}
</style>
